<template>
  <div>
    <template v-for="(item, index) in options">
      <template v-if="values.includes(String(item[type]))">
        <el-tag
          :disable-transitions="true"
          :key="item.userId"
          :index="index"
        >
          {{ item.nickName + ' ' }}
        </el-tag>
      </template>
    </template>
    <template v-if="unmatch && showValue">
      {{ unmatchArray | handleArray }}
    </template>
  </div>
</template>

<script>
import { getNormalUserInfo } from "@/api/system/user"
export default {
  name: "UserTag",
  props: {
    type: {
      type: String,
      default: "userId"
    },
    value: [Number, String, Array],
    // 当未找到匹配的数据时，显示value
    showValue: {
      type: Boolean,
      default: true,
    },
    separator: {
      type: String,
      default: ","
    }
  },
  data() {
    return {
      unmatchArray: [], // 记录未匹配的项
      // 用户信息
      options: [],
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      getNormalUserInfo().then(res => {
        this.options = res.data
      })
    }
  },
  computed: {
    values() {
      if (this.value === null || typeof this.value === 'undefined' || this.value === '') return []
      return Array.isArray(this.value) ? this.value.map(item => '' + item) : String(this.value).split(this.separator)
    },
    unmatch() {
      this.unmatchArray = []
      // 没有value不显示
      if (this.value === null || typeof this.value === 'undefined' || this.value === '' || this.options.length === 0) return false
      // 传入值为数组
      let unmatch = false // 添加一个标志来判断是否有未匹配项
      this.values.forEach(item => {
        // 按 type 字段匹配，并统一转字符串比较
        const isMatch = this.options.some(v => String(v[this.type]) === item );

        if (!isMatch) {
          this.unmatchArray.push(item);
          unmatch = true;
        }
      });
      return unmatch // 返回标志的值
    },

  },
  filters: {
    handleArray(array) {
      if (array.length === 0) return '';
      return array.reduce((pre, cur) => {
        return pre + ' ' + cur;
      })
    },
  }
};
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
